package com.sunyur.tailor.channel.config.middle;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @description kafka发送端配置类
 */
@Configuration
@ConditionalOnProperty(name = "spring.kafka.switch", havingValue = "open")
public class KafkaProducerConfig {
    @Value("${spring.kafka.producer.retries}")
    private int retries;
    @Value("${spring.kafka.producer.batch-size}")
    private int batchSize;
    @Value("${spring.kafka.producer.buffer-memory}")
    private int bufferMemory;
    @Value("${spring.kafka.producer.linger-ms}")
    private String lingerMs;
    @Value("${spring.kafka.producer.acks-config}")
    private String acksConfig;

	/**
	 * oa bootstrap-servers地址
	 */
    @Value("${spring.kafka.oa.bootstrap-servers}")
    private String oaServers;
    /**
     * mdm bootstrap-servers地址
     */
    @Value("${spring.kafka.mdm.bootstrap-servers}")
    private String mdmServers;

    /**
     * @Description: 生产者配置
     */
    private Map<String,Object> producerConfig(String servers) {
    	Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        props.put(ProducerConfig.RETRIES_CONFIG, retries);
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize);
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferMemory);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.ACKS_CONFIG, acksConfig);
        props.put(ProducerConfig.LINGER_MS_CONFIG, lingerMs);
        return props;
    }

    /**
     * @Description: oa kafkaTemplate
     */
    @Bean
    public KafkaTemplate oaKafkaTemplate() {
        return new KafkaTemplate(new DefaultKafkaProducerFactory<String, String>(producerConfig(oaServers)));
    }

    /**
     * @Description: mdm kafkaTemplate
     */
	@Bean
    public KafkaTemplate mdmKafkaTemplate() {
    	return new KafkaTemplate(new DefaultKafkaProducerFactory<String, String>(producerConfig(mdmServers)));
    }
}
